﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZQNB.BaseLib.Core.Models;
using ZQNB.Common;
using ZQNB.Common.Models;

namespace ZQNB.BaseLib.Core.Services
{
    public class NavMenuService : INavMenuService
    {
        private readonly CoreDataHelper _coreDataHelper;

        public NavMenuService(CoreDataHelper coreDataHelper)
        {
            _coreDataHelper = coreDataHelper;
        }

        public void Init(IList<NavMenu> models, bool replaceExist = false)
        {
            var currentModels = _coreDataHelper.Read<NavMenu>().OrderBy(x => x.SortNum).ToList();
            foreach (var model in models)
            {
                var theMenu = currentModels.SingleOrDefault(x => model.Pk.NbEquals(x.Pk));
                if (theMenu == null)
                {
                    var theCopy = SimpleMapper.ToModel<NavMenu, NavMenu>(model);
                    currentModels.Add(theCopy);
                }
                else
                {
                    if (replaceExist)
                    {
                        var theCopy = SimpleMapper.ToModel<NavMenu, NavMenu>(model);
                        currentModels.Remove(theMenu);
                        currentModels.Add(theCopy);
                    }
                }
            }

            var toSave = currentModels.OrderBy(x => x.SortNum).ToList();
            _coreDataHelper.Save(toSave);

        }

        public void Validate(IList<NavMenu> models)
        {
            //pk不能重复
            foreach (var model in models)
            {
                int count = models.Count(x => x.Pk.NbEquals(model.Pk));
                if (count > 1)
                {
                    throw new ArgumentException(string.Format("Pk{0}存在重复", model.Pk));
                }
            }
        }

        public IList<NavMenu> GetNavMenus()
        {
            var models = _coreDataHelper.Read<NavMenu>().OrderBy(x => x.SortNum).ToList();
            return models;
        }
    }
}
